# -*- coding: utf-8 -*-

import logging
from wolfox.foxit.base.tutils import parseName

logger = logging.getLogger("foxit.source.reader")

class NullFilter(object):
    def filter(self,record):
        return True

nullFilter = NullFilter()

class DateFilter(object):   #只能做filter链条末端的filter，不设置innerFilter
    __slots__ = "begin","end"

    def __init__(self,begin=0,end=99999999):
        self.begin = begin
        self.end = end

    def filter(self,record):
        return self.begin <= record.tdate < self.end

class CodeFilter(object):
    __slots__ = "codes","nextFilter"

    def __init__(self,codes,nextFilter=nullFilter): #codes为Set类型
        self.codes = codes
        self.nextFilter = nextFilter
        
    def filter(self,record):
        return (record.tstock in self.codes) and self.nextFilter.filter(record)


class Reader(object):
    __slots__ = "extractor","filter"

    def __init__(self,extractor,filter=nullFilter):
        self.extractor = extractor
        self.filter = filter

    def read(self,filename):
        fh = open(filename,"rb")    #如果文件无法打开，则必须直接返回异常
        records = self.read2(fh,parseName(filename))
        fh.close()
        return records

    def read2(self,filehandle,name):
        records = []
        try:
            self.extractor.handleHeader(filehandle,name)
            record = self.extractor.extract(filehandle)
            while(record):
                if(self.filter.filter(record)):
                    records.append(record)
                record = self.extractor.extract(filehandle)                
        except Exception, inst:
            #logger.warn(u"文件读取异常：" + str(inst).decode('gbk'))
            logger.exception(inst)
        return records


